<template>
  <div>
    <div v-if="collapse" v-for="(item, i) in list" style="display:flex;gap:10px">
      <el-form-item v-for="field in children">
        <component v-model="list[i][field?.prop]" v-bind="componentProps(field)">
          <el-option v-for="o in field.options" :value="o">{{ o }}</el-option>
        </component>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-plus" @click="addOption(i)" circle></el-button>
        <el-button icon="el-icon-delete" @click="delOption(i)" circle></el-button>
      </el-form-item>
    </div>
    <div>
      <el-button @click="addOption(0)" v-if="list.length === 0" icon="el-icon-plus">添加</el-button>
      <template v-else>
        <el-badge v-if="!collapse" :value="list.length">
          <el-button @click="$emit('update:collapse',true)" icon="el-icon-remove-outline">展开</el-button>
        </el-badge>
        <el-button v-if="collapse" @click="$emit('update:collapse', false)" icon="el-icon-circle-plus-outline">收起</el-button>
      </template>
    </div>
  </div>
</template>

<script>
import elFormItems from '@/utils/formUtils'
export default {
  name: 'object-array',
  props: ['value', 'columns', 'children', 'collapse'],
  computed: {
    list: {
      get () {
        return this.value || []
      },
      set(a,b,c,d){
        console.log(a,b,c,d)
      }
    }
  },
  methods:{
    delOption(index) {
      const data = this.list
      data.splice(index, 1)
      this.$emit('input', data)
    },
    addOption(index) {
      const data = this.list
      data.splice(index + 1, 0, {})
      this.$emit('input', data)
      this.$emit('update:collapse',true)
    },
    componentProps(item) {
      const elItem = elFormItems.find(i => i.value === item.type)
      const placeholder = `请${['input'].includes(item.type)?'输入':'选择'}${item.label}`
      let props = { ...elItem, placeholder, ...item.props }
      console.log(props)
      if (!elItem) {
        props.is = item.type
      }
      if (item.type === 'cascader') {
        props.options = item.options
      }
      delete props.value
      return props
    }
  }
}
</script>

<style lang="scss" scoped>
.table-button {
  display: flex; 
  justify-content: space-between;

  a {
    cursor: pointer;
  }
}
</style>